<route lang="jsonc" type="page">
    {
      "style": {
			"navigationStyle": "custom",
			"navigationBarTitleText": "订单信息"
		}
    }
</route>

<script lang="ts" setup>
	import { useSafeAreaInsets } from '@/mixins/basic'
	import { Service } from '@/api/home'
	import { useOrder } from '@/store/order'
	import FabServices from '@/pages/components/services.vue'
	import { ref } from 'vue'
	import Basic from './basic.vue'
	import ServiceItem from './service-item'
	import { getServiceDetails } from '@/api/maintenance'
	import DeliverMethod from './delivery-method'
	import HeaderNavbar from '@/pages/components/header-navbar.vue'
	// import { useToast } from 'wot-design-uni'
	// const toast = useToast()
	// console.log(useToast)
	const orderStore = useOrder()

	defineOptions({
		name: 'OrderInfo',
	})
	
	const { safeAreaInsets } = useSafeAreaInsets()
	const active = ref<string[]>(['item1', 'delivery1', 'delivery2'])
	const serviceList = ref([])
	// 雪具收取实例
	const deliverRef1 = ref()
	// 雪具寄送实例
	const deliverRef2 = ref()

	// 获取选中的明细列表
	const getSelectData = computed(() => {
		const deepList = JSON.parse(JSON.stringify(serviceList.value))
		const data = deepList.filter((item: AnyObject) => {
			const isSelect = item.children.find((child: AnyObject) => child.select)
			if (!isSelect) return false
			// 过滤出选中的列表
			let children = item.children.filter((child: AnyObject) => child.select)
			children.forEach((child: AnyObject) => {
				child.price = Number(child.price).toFixed(2)
			})

			item.children = children
			return item
		})

		return data
	})
	// 合计总金额
	const summaryMoney = computed(() => {
		const priceArr = getSelectData.value.map((item: AnyObject) => {
			return item.children.map(map => Number(map.price))
		}).flat()

		const total = priceArr.reduce((prev: any, curr: any) => {
			// 累加总价
			return prev + curr
		}, 0)

		return total.toFixed(2)
	})
	
	onMounted(() => {
		initData()
	})
	
	function initData() {
		getServiceDetails().then(res => {
			// res.forEach(item => {
			// 	const targetArr = item.children.map((item: AnyObject) => item.service_target)
			// 	// 存在单板、双板的children，重新修改数据渲染方式
			// 	if (targetArr.includes('0') && targetArr.includes('1')) {}
			// })
			console.log(orderStore.orderInfo)
			// 找到当前点进的商品信息，并放在数据第一位
			const index = res.findIndex((el: AnyObject) => el.id === orderStore.orderInfo.id)
			const item = res[index]
			res.splice(index, 1)
			res.unshift(item)
			res.forEach((item: AnyObject) => {
				item.children.forEach((el: AnyObject) => {
					el.select_thickness_1 = '默认'
					el.select_thickness_2 = '默认'
				})
			})
			serviceList.value = res
		})
	}
	
	// 下单
	async function handleOrder() {
		if (orderStore.orderInfo.eq_id === '') return uni.showToast({
			icon: 'none',
			title: '请选择雪具'
		})
		if (!orderStore.orderInfo.eq_photo) {
			return uni.showToast({
				icon: 'none',
				title: '请上传雪具照片'
			})
		}
		
		if (orderStore.selectStore.id === undefined) {
			uni.showToast({
				icon: 'none',
				title: '请选择门店'
			})
			return
		}
		// 雪具收取，店家取货校验地址填写
		if (!deliverRef1.value.showStoreList) {
			const { valid } = await deliverRef1.value.checkFormData()

			if (!valid) return

			// 存储地址信息到本地
			uni.setStorageSync('addressInfo1', deliverRef1.value.formData)
		}
		// 雪具寄送，快递或者店家送货，校验地址填写
		if (!deliverRef2.value.showStoreList) {
			const { valid } = await deliverRef2.value.checkFormData()

			if (!valid) return

			// 存储地址信息到本地
			uni.setStorageSync('addressInfo2', deliverRef2.value.formData)
		}

		if (summaryMoney.value <= 0) return uni.showToast({
			icon: 'none',
			title: '请选择服务项目'
		})
		
		// 设置运费
		const { way, kd_type } = orderStore.orderInfo
		const express_fee = (way === '2' && kd_type === '2')
		  ? 80
		  : (way === '2' || kd_type === '2')
		    ? 50
		    : 0
		
		orderStore.setOrderInfo({
			selectServices: getSelectData.value,
			express_fee
			// totalMoney: summaryMoney.value
		})

		uni.navigateTo({
			url: '/pages-sub/order/summary'
		})
	}
</script>

<template>
	<view class="info-page" :style="{ marginTop: `${safeAreaInsets?.top}px` }">
		<header-navbar title="订单信息" />

		<!-- accordion -->
		<wd-collapse v-model="active" custom-class="collapse-box">
			<!-- 基础信息 -->
			<Basic />
			<!-- 服务列表 -->
			<ServiceItem v-for="item in serviceList" :key="item.id" :data="item" />
			<!-- 雪具收取 -->
			<DeliverMethod ref="deliverRef1" :types='1' />
			<!-- 雪具寄送 -->
			<DeliverMethod ref="deliverRef2" :types='2' />
		</wd-collapse>

		<view class="fixed-btn" :style="{ paddingBottom: safeAreaInsets?.bottom > 0 ? `${safeAreaInsets?.bottom}px` : null }">
			<!-- 客服按钮 -->
			<FabServices :bottom='300' />

			<!-- 选中的明细列表 -->
			<view class="details-list">
				<view v-for="item in getSelectData" :key="item.id" class="details-item">
					<view class="category-name">{{ item.name }}</view>
					<view v-for="child in item.children" :key="child.id" class="child-info flex-between">
						<view class="name">{{ child.name }}</view>
						<view class="price">¥ {{ child.price }}</view>
					</view>
				</view>
			</view>
			<view class="total-money flex-between">
				<view>总计</view>
				<view>¥ {{ summaryMoney }}</view>
			</view>
			<view class="btn-order" @click="handleOrder">立即下单</view>
		</view>
	</view>
</template>

<style lang="scss" scoped>
	.info-page {
		background-color: #FCFEFF;
		// padding-bottom: 150px;
		
		:deep(.collapse-box) {
			padding-top: 44px;
			.collapse-item {
				margin-top: 20px;
			}
		}

		.fixed-btn {
			:deep(.service-fab) {
				position: absolute;
				top: -55px;
			}
			
			.details-list {
				padding: 11px 0 19px 0;
				border-bottom: 1px solid #E6E6E6;
			}
		}
	}
</style>